import React, { Component } from 'react'
import { Button, Table, Space, Col } from 'antd';
import uniqid from "uniqid";
import { DownloadOutlined } from '@ant-design/icons';
import XLSX from 'xlsx';
import posittyData from './jsondata/positty.json'

interface Props {

}
interface State {

}


//货位信息
export default class List extends Component<Props, State> {

  props = {
    handleEditPositty: (record: any) => { },
    handleSelectPositty: (record: any) => { }
  }

  /**
 * 编辑货位
 * @param record 
 */
  editPositty = (record: any) => {
    console.log(record)
    //将数据传给index父组件
    this.props.handleEditPositty(record)
  }
  /**
   * 查看供应商
   * @param record
   */
  selectPositty = (record: any) => {
    console.log(record);
    //将数据传给index父组件
    this.props.handleSelectPositty(record);
  };
  columns = [
    {
      title: '代码',
      dataIndex: 'code',
      key: 'code',
      render: (text: any) => <a>{text}</a>,
      sorter: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
    },
    {
      title: '长度(cm)',
      dataIndex: 'length',
      key: 'length',
    },
    {
      title: '宽度(cm)',
      dataIndex: 'breadth',
      key: 'breadth',
      render: (text: any) => <a>{text}</a>,
    },
    {
      title: '高度(cm)',
      dataIndex: 'height',
      key: 'height',
    },
    {
      title: '承重',
      dataIndex: 'bearing',
      key: 'bearing',
    },
    {
      title: '容积率(%)',
      dataIndex: 'plotratio',
      key: 'plotratio',
    },
    {
      title: '容积率(%)',
      dataIndex: 'traynumber',
      key: 'traynumber',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <a href='javascript:;' onClick={() => this.selectPositty(record)}>查看</a>
          <a href='javascript:;' onClick={() => this.editPositty(record)}>编辑</a>
        </Space>
      ),
    },
  ];

  data = posittyData.datalist;
  exldata = [
    {
      key: "",
      code: "",
      name: "",
      length: 0,
      breadth: 0,
      height: 0,
      bearing: 2000,
      action: ["", ""],
      plotratio: 0,
      traynumber: 0
    }
  ]; //批量导出的数据

  componentDidMount = () => {

  }

  state = {
    state: false,
    pagination: {
      total: this.data.length,
      showTotal: (total: any) => {
        return `共 ${total} 条`;
      },
      defaultPageSize: 60,
      defaultCurrent: 1,
      showSizeChanger: true
    },
    selectedRowKeys: new Array(),
    loading: false
  }


  setCheckStrictly = (stats: boolean) => {
    this.setState({
      state: { stats }
    })
  }

  //选中记录
  onSelectChange = (selectedRowKeys: any) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  batchRemove = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };
  //勾选记录导出 
  batchExport = () => {

    //根据勾选的key进行批量导出 
    //选中的的记录id this.state.selectedRowKeys
    console.log(this.state.selectedRowKeys)
    console.log(this.data)

    //根据选中的数据导出到excel
    this.exldata = [];
    for (let j = 0; j < this.data.length; j++) {
      let item = this.data[j];
      if (this.state.selectedRowKeys.indexOf(item.key) > -1) {
        this.exldata.push(item);
      }
    }
    //删除操作字段
    this.columns.forEach((item) => {
      if (item.key === "action") {
        this.pull(this.columns, item.key);
      }
    });
    this.exportExcel(this.columns, this.exldata, "货位信息.xlsx");

  }
  //删除数组对象某个字段
  pull = (arr: any, str: any) => {
    //获取指定元素的索引
    var index = arr.indexOf(str);
    //使用splice()删除指定元素
    arr.splice(index, 1);
  };
  /**  
   * 删除指定的元素给
   */
  pullElement = () => {
    //删除操作字段
    this.columns.forEach((item) => {
      if (item.key === "action") {
        this.pull(this.columns, item.key);
      }
    });
    this.exportExcel(this.columns, this.data, "货位信息.xlsx")
    console.log("item：", this.columns);
  }
  /**
   * 导出excel函数
   * @param headers 列名
   * @param data  数据
   * @param fileName 文件名 
   */
  exportExcel = (headers: any, data: any, fileName = '货位信息表.xlsx') => {
    const _headers = headers
      .map((item: any, i: any) => Object.assign({}, { key: item.key, title: item.title, position: String.fromCharCode(65 + i) + 1 }))
      .reduce((prev: any, next: any) => Object.assign({}, prev, { [next.position]: { key: next.key, v: next.title } }), {});

    const _data = data
      .map((item: any, i: any) => headers.map((key: any, j: any) => Object.assign({}, { content: item[key.key], position: String.fromCharCode(65 + j) + (i + 2) })))
      // 对刚才的结果进行降维处理（二维数组变成一维数组）
      .reduce((prev: any, next: any) => prev.concat(next))
      // 转换成 worksheet 需要的结构
      .reduce((prev: any, next: any) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});

    // 合并 headers 和 data
    const output = Object.assign({}, _headers, _data);
    // 获取所有单元格的位置
    const outputPos = Object.keys(output);
    // 计算出范围 ,["A1",..., "H2"]
    const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;

    // 构建 workbook 对象
    const wb = {
      SheetNames: ['mySheet'],
      Sheets: {
        mySheet: Object.assign(
          {},
          output,
          {
            '!ref': ref,
            '!cols': [{ wpx: 45 }, { wpx: 100 }, { wpx: 200 }, { wpx: 80 }, { wpx: 150 }, { wpx: 100 }, { wpx: 300 }, { wpx: 300 }],
          },
        ),
      },
    };
    // 导出 Excel 
    XLSX.writeFile(wb, fileName);
  }
  render() {
    const { pagination, selectedRowKeys, loading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div>
        <div style={{ marginLeft: '8px', marginTop: '10px', marginBottom: '10px' }}>
          <Col span={6}>
            <Space style={{ float: 'right' }}>
              <Button key={uniqid()} type="primary" onClick={this.batchRemove} disabled={!hasSelected} loading={loading}>
                批量删除
                    </Button>
              <Button key={uniqid()} type="primary" icon={<DownloadOutlined />} onClick={this.batchExport} disabled={!hasSelected} loading={loading}>
                批量导出
                                </Button>
              <Button key={uniqid()} type="primary" icon={<DownloadOutlined />} onClick={this.pullElement}>
                全部导出
                                </Button>
            </Space>
          </Col>
        </div>
        <div style={{ marginBottom: 10 }}>
          {/* <Divider /> */}
          <Table rowSelection={rowSelection} bordered={true} columns={this.columns} dataSource={this.data} pagination={pagination} />
        </div>
      </div>
    )
  }
}
